<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 会员卡申请追加
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m310030_000009_t_vipcard_card_apply_append extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%card_apply}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from('{{%card_order}}')->andWhere(['!=', 'expired_at', 0]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * @inheritdoc
     */
    public function filterData(&$data) {
        if (!parent::validateTransfer($data)) {
            return false;
        }
        return true;
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        $items = [];
        foreach ($rows as $row) {
            if (!$migration->filterData($row)) {
                continue;
            }
            $items[] = [
                'order_id' => $row['id'],
                'user_id' => $row['user_id'],
                'type_id' => $row['type_id'],
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
                'scope' => 1,
                'status' => 0,
            ];
        }
        if (empty($items)) {
            return;
        }
        $connect->batchInsert('{{%card_apply}}', [
            'order_id',
            'user_id',
            'type_id',
            'created_at',
            'updated_at',
            'scope',
            'status',
        ], $items)->execute();
    }

}
